/**
 * Copyright (c) 2006 George Malamidis, nutrun.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies
 * or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * $Author$
 * $Rev$
 */

package aerie.controller;

import groovy.lang.GroovyClassLoader;
import groovy.util.ResourceException;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ControllerPool {
    private static final String ROOT_PATH = "";

    private Map controllers = new HashMap();
    private File dir;
    private static long lastModifiedTime;
    private static GroovyClassLoader groovyClassLoader;

    public ControllerPool(File dir) {
        this.dir = dir;
        loadControllers(this.dir, ROOT_PATH);
    }

    public Controller getInstanceOf(String controller) throws ResourceException {

        if (lastModifiedTime != dir.lastModified()) loadControllers(dir, ROOT_PATH);

        controller = controller.toLowerCase();

        if (!controllers.containsKey(controller)) {
            throw new ResourceException("Controller [" + controller + "] not found");
        }

        return ((CachedController) controllers.get(controller)).getControllerClone();
    }

    private void loadControllers(File dir, String path) {
        lastModifiedTime = this.dir.lastModified();
        groovyClassLoader = new GroovyClassLoader(getClass().getClassLoader());        
        final File[] files = dir.listFiles();
        File file;
        //noinspection ForLoopReplaceableByForEach
        for (int i = 0; i < files.length; i++) {
            file = files[i];
            String filename = file.getName();
            if (file.isDirectory()) {
                loadControllers(file, filename);
            } else if ( filename.endsWith(".groovy") ) {
                loadControllerFrom(file, path);
            }
        }
    }

    private void loadControllerFrom(File file, String path) {
        try {
            final Object controller = groovyClassLoader.parseClass(file).newInstance();
            if (controller instanceof Controller) {
                CachedController cachedController = new CachedController((Controller) controller, file);
                //noinspection unchecked
                controllers.put(getFullControllerName(controller, path), cachedController);
            }
        } catch (InstantiationException e) {
            throw new RuntimeException("Unable to instantiate controller [" + file.getName() + "]", e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException("Controller [" + file.getName() + "] not found", e);
        }
    }

    /**
     * For testing only
     * @return the map of loaded Controllers
     */
    Map getControllers() {
        return controllers;
    }

    private String getFullControllerName(Object controller, String path) {
        path = path.equals(ROOT_PATH) ? path : path + "/";
        return path + controller.getClass().getName().toLowerCase();
    }
}
